package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo18PI {

  def main(args: Array[String]): Unit = {


    val conf: SparkConf = new SparkConf()
      .setAppName("student")
    ///提交到服务器运行需要注释掉
    //.setMaster("local")

    val sc = new SparkContext(conf)

    val list: Range = 0 until 100000000

    //构建按一个很大的rdd
    val listRDD: RDD[Int] = sc.parallelize(list)


    //模拟生成点
    val pointRDD: RDD[(Double, Double)] = listRDD.map(i => {
      //模拟点
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1

      (x, y)
    })

    //取出园内的点
    val yuanPointRDD: RDD[(Double, Double)] = pointRDD.filter {
      case (x: Double, y: Double) =>

        //计算点到圆心的距离
        x * x + y * y <= 1
    }

    //计算PI
    val PI: Double = yuanPointRDD.count().toDouble / list.length * 4.0


    println("PI ：" + PI)
  }

}
